namespace SubSonic.Utilities
{
    using SubSonic;
    using SubSonic.Sugar;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Globalization;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class Utility
    {
        public static string ByteArrayToString(byte[] arrInput)
        {
            StringBuilder builder = new StringBuilder(arrInput.Length * 2);
            for (int i = 0; i < arrInput.Length; i++)
            {
                builder.Append(arrInput[i].ToString("x2"));
            }
            return builder.ToString();
        }

        public static object ChangeType(object value, Type conversionType)
        {
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            }
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                {
                    return null;
                }
                NullableConverter converter = new NullableConverter(conversionType);
                conversionType = converter.UnderlyingType;
            }
            return Convert.ChangeType(value, conversionType);
        }

        public static string CheckStringLength(string stringToCheck, int maxLength)
        {
            if (stringToCheck.Length > maxLength)
            {
                if ((stringToCheck.Length > maxLength) && (stringToCheck.IndexOf(" ") == -1))
                {
                    return (stringToCheck.Substring(0, maxLength) + "...");
                }
                if (stringToCheck.Length > 0)
                {
                    return (stringToCheck.Substring(0, maxLength) + "...");
                }
            }
            return stringToCheck;
        }

        public static string DataTableToHTML(DataTable tbl, string tableWidth)
        {
            StringBuilder builder = new StringBuilder();
            if (string.IsNullOrEmpty(tableWidth))
            {
                tableWidth = "70%";
            }
            if (tbl != null)
            {
                builder.Append("<table width=\"");
                builder.Append(tableWidth);
                builder.Append("\" cellpadding=\"4\" cellspacing=\"0\">");
                builder.Append("<thead bgcolor=\"gainsboro\">");
                foreach (DataColumn column in tbl.Columns)
                {
                    builder.Append("<th><b>");
                    builder.Append(column.ColumnName);
                    builder.Append("</b></th>");
                }
                builder.Append("</thead>");
                bool flag = false;
                foreach (DataRow row in tbl.Rows)
                {
                    if (flag)
                    {
                        builder.Append("<tr>");
                    }
                    else
                    {
                        builder.Append("<tr bgcolor=\"whitesmoke\">");
                    }
                    foreach (DataColumn column2 in tbl.Columns)
                    {
                        builder.Append("<td>");
                        builder.Append(row[column2].ToString());
                        builder.Append("</td>");
                    }
                    builder.Append("</tr>");
                    flag = !flag;
                }
                builder.Append("</table>");
            }
            return builder.ToString();
        }

        public static string FastReplace(string original, string pattern, string replacement, StringComparison comparisonType)
        {
            if (original == null)
            {
                return null;
            }
            if (string.IsNullOrEmpty(pattern))
            {
                return original;
            }
            int length = pattern.Length;
            int num2 = -1;
            int startIndex = 0;
            StringBuilder builder = new StringBuilder();
            while (true)
            {
                num2 = original.IndexOf(pattern, num2 + 1, comparisonType);
                if (num2 < 0)
                {
                    builder.Append(original, startIndex, original.Length - startIndex);
                    return builder.ToString();
                }
                builder.Append(original, startIndex, num2 - startIndex);
                builder.Append(replacement);
                startIndex = num2 + length;
            }
        }

        public static string FormatDate(DateTime theDate)
        {
            return FormatDate(theDate, false, null);
        }

        public static string FormatDate(DateTime theDate, bool showTime)
        {
            return FormatDate(theDate, showTime, null);
        }

        public static string FormatDate(DateTime theDate, bool showTime, string pattern)
        {
            string str = "MMMM d, yyyy";
            string str2 = "hh:mm tt";
            if (pattern == null)
            {
                if (showTime)
                {
                    pattern = str + " " + str2;
                }
                else
                {
                    pattern = str;
                }
            }
            return theDate.ToString(pattern);
        }

        public static object GetDefaultControlValue(TableSchema.TableColumn col, Control ctrl, bool isAdd, bool returnDBNull)
        {
            object name = null;
            string columnName = col.ColumnName;
            if (IsMatch(columnName, "ModifiedBy"))
            {
                name = HttpContext.Current.User.Identity.Name;
            }
            else if (IsMatch(columnName, "ModifiedOn"))
            {
                name = DateTime.Now;
            }
            else if (IsMatch(columnName, "CreatedBy"))
            {
                if (isAdd)
                {
                    name = HttpContext.Current.User.Identity.Name;
                }
                else if (ctrl != null)
                {
                    name = ((Label) ctrl).Text;
                }
            }
            else if (IsMatch(columnName, "CreatedOn"))
            {
                if (isAdd)
                {
                    name = DateTime.Now;
                }
                else if (ctrl != null)
                {
                    name = ((Label) ctrl).Text;
                }
            }
            else if (ctrl is TextBox)
            {
                name = ((TextBox) ctrl).Text;
            }
            else if (ctrl is CheckBox)
            {
                name = ((CheckBox) ctrl).Checked;
            }
            else if (ctrl is DropDownList)
            {
                name = ((DropDownList) ctrl).SelectedValue;
            }
            else if (ctrl is System.Web.UI.WebControls.Calendar)
            {
					System.Web.UI.WebControls.Calendar calendar = (System.Web.UI.WebControls.Calendar)ctrl;
                if (calendar.SelectedDate > DateTime.MinValue)
                {
						 name = ((System.Web.UI.WebControls.Calendar)ctrl).SelectedDate;
                }
                else if (col.IsNullable)
                {
                    name = null;
                }
                else
                {
                    name = DateTime.Now.Date;
                }
            }
            else if (ctrl is Label)
            {
                name = ((Label) ctrl).Text;
            }
            if ((col.IsPrimaryKey || col.AutoIncrement) || ((name != null) && (name.ToString().Length != 0)))
            {
                return name;
            }
            if (col.IsNullable)
            {
                if (returnDBNull)
                {
                    return DBNull.Value;
                }
                return null;
            }
            return GetDefaultSetting(col);
        }

        public static object GetDefaultSetting(TableSchema.TableColumn column)
        {
            if (column.IsNullable)
            {
                return null;
            }
            if (IsMatch(column.ColumnName, "CreatedOn") || IsMatch(column.ColumnName, "ModifiedOn"))
            {
                return DateTime.Now;
            }
            if (IsLogicalDeleteColumn(column.ColumnName))
            {
                return false;
            }
            switch (column.DataType)
            {
                case DbType.AnsiStringFixedLength:
                case DbType.StringFixedLength:
                case DbType.Xml:
                case DbType.String:
                case DbType.AnsiString:
                    return string.Empty;

                case DbType.Boolean:
                    return false;

                case DbType.Date:
                case DbType.DateTime:
                    return new DateTime(0x76c, 1, 1);

                case DbType.Guid:
                    return Guid.Empty;
            }
            return 0;
        }

        public static string GetDefaultValue(TableSchema.TableColumn col, ICodeLanguage language)
        {
            return language.GetDefaultValue(col.ColumnName, col.DataType, false);
        }

        public static int GetEffectiveMaxLength(TableSchema.TableColumn col)
        {
            if ((col.DataType == DbType.String) && (col.MaxLength == -1))
            {
                return 0x7fffffff;
            }
            return col.MaxLength;
        }

        [Obsolete("Obsolete and marked for removal. Kept for compatibility with 2.0.1 Starter Site. Update references to use Sugar.Files.GetFileText()")]
        public static string GetFileText(string absolutePath)
        {
            return Files.GetFileText(absolutePath);
        }

        public static Guid GetGuidParameter(string sParam)
        {
            Guid empty = Guid.Empty;
            if (HttpContext.Current.Request.QueryString[sParam] != null)
            {
                string guid = HttpContext.Current.Request[sParam];
                if (Validation.IsGuid(guid))
                {
                    empty = new Guid(guid);
                }
            }
            return empty;
        }

        public static int GetIntParameter(string sParam)
        {
            int result = 0;
            if (HttpContext.Current.Request.QueryString[sParam] != null)
            {
                string str = HttpContext.Current.Request[sParam];
                if (!string.IsNullOrEmpty(str))
                {
                    int.TryParse(str, out result);
                }
            }
            return result;
        }

        public static string GetParameter(string sParam)
        {
            if (HttpContext.Current.Request.QueryString[sParam] != null)
            {
                return HttpContext.Current.Request[sParam];
            }
            return string.Empty;
        }

        public static string GetParameterName(string name, DataProvider provider)
        {
            if (string.IsNullOrEmpty(name))
            {
                return string.Empty;
            }
            string word = name;
            word = GetProperName(Replace(word, provider.StripParamText, string.Empty, provider.RemoveUnderscores), provider);
            word = IsStringNumeric(word) ? ("_" + word) : word;
            return KeyWordCheck(StripNonAlphaNumeric(word).Replace("@", string.Empty).Trim(), string.Empty, provider);
        }

        public static string GetProperName(string sIn)
        {
            string str = Inflector.ToPascalCase(sIn);
            if (str.EndsWith("TypeCode"))
            {
                str = str.Substring(0, str.Length - 4);
            }
            return str;
        }

        public static string GetProperName(string sIn, DataProvider provider)
        {
            string text = sIn;
            if (provider.FixDatabaseObjectCasing)
            {
                text = Inflector.ToPascalCase(text, provider.RemoveUnderscores);
            }
            if (text.EndsWith("TypeCode"))
            {
                text = text.Substring(0, text.Length - 4);
            }
            return text;
        }

        public static string GetRandomString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomString(4, false));
            builder.Append(RandomInt(0x3e8, 0x270f));
            builder.Append(RandomString(2, false));
            return builder.ToString();
        }

        public static string GetSiteRoot()
        {
            string str = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            switch (str)
            {
                case null:
                case "80":
                case "443":
                    str = string.Empty;
                    break;

                default:
                    str = ":" + str;
                    break;
            }
            string str2 = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
            switch (str2)
            {
                case null:
                case "0":
                    str2 = "http://";
                    break;

                default:
                    str2 = "https://";
                    break;
            }
            string applicationPath = HttpContext.Current.Request.ApplicationPath;
            if (applicationPath == "/")
            {
                applicationPath = string.Empty;
            }
            return (str2 + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + str + applicationPath);
        }

        public static SqlDbType GetSqlDBType(DbType dbType)
        {
            switch (dbType)
            {
                case DbType.AnsiString:
                    return SqlDbType.VarChar;

                case DbType.Binary:
                    return SqlDbType.VarBinary;

                case DbType.Byte:
                    return SqlDbType.TinyInt;

                case DbType.Boolean:
                    return SqlDbType.Bit;

                case DbType.Currency:
                    return SqlDbType.Money;

                case DbType.Date:
                    return SqlDbType.DateTime;

                case DbType.DateTime:
                    return SqlDbType.DateTime;

                case DbType.Decimal:
                    return SqlDbType.Decimal;

                case DbType.Double:
                    return SqlDbType.Float;

                case DbType.Guid:
                    return SqlDbType.UniqueIdentifier;

                case DbType.Int16:
                    return SqlDbType.Int;

                case DbType.Int32:
                    return SqlDbType.Int;

                case DbType.Int64:
                    return SqlDbType.BigInt;

                case DbType.Object:
                    return SqlDbType.Variant;

                case DbType.SByte:
                    return SqlDbType.TinyInt;

                case DbType.Single:
                    return SqlDbType.Real;

                case DbType.String:
                    return SqlDbType.NVarChar;

                case DbType.Time:
                    return SqlDbType.DateTime;

                case DbType.UInt16:
                    return SqlDbType.Int;

                case DbType.UInt32:
                    return SqlDbType.Int;

                case DbType.UInt64:
                    return SqlDbType.BigInt;

                case DbType.VarNumeric:
                    return SqlDbType.Decimal;

                case DbType.AnsiStringFixedLength:
                    return SqlDbType.Char;

                case DbType.StringFixedLength:
                    return SqlDbType.NChar;
            }
            return SqlDbType.VarChar;
        }

        public static string GetSystemType(DbType dbType)
        {
            switch (dbType)
            {
                case DbType.AnsiString:
                    return "System.String";

                case DbType.Binary:
                    return "System.Byte[]";

                case DbType.Byte:
                    return "System.Byte";

                case DbType.Boolean:
                    return "System.Boolean";

                case DbType.Currency:
                    return "System.Decimal";

                case DbType.Date:
                    return "System.DateTime";

                case DbType.DateTime:
                    return "System.DateTime";

                case DbType.Decimal:
                    return "System.Decimal";

                case DbType.Double:
                    return "System.Double";

                case DbType.Guid:
                    return "System.Guid";

                case DbType.Int16:
                    return "System.Int16";

                case DbType.Int32:
                    return "System.Int32";

                case DbType.Int64:
                    return "System.Int64";

                case DbType.Object:
                    return "System.Object";

                case DbType.SByte:
                    return "System.SByte";

                case DbType.Single:
                    return "System.Single";

                case DbType.String:
                    return "System.String";

                case DbType.Time:
                    return "System.TimeSpan";

                case DbType.UInt16:
                    return "System.UInt16";

                case DbType.UInt32:
                    return "System.UInt32";

                case DbType.UInt64:
                    return "System.UInt64";

                case DbType.VarNumeric:
                    return "System.Decimal";

                case DbType.AnsiStringFixedLength:
                    return "System.String";

                case DbType.StringFixedLength:
                    return "System.String";
            }
            return "System.String";
        }

        public static string GetVariableType(DbType dbType, bool isNullableColumn, ICodeLanguage language)
        {
            return language.GetVariableType(dbType, isNullableColumn);
        }

        public static bool IsAuditField(string colName)
        {
            if ((!IsMatch(colName, "CreatedBy") && !IsMatch(colName, "CreatedOn")) && !IsMatch(colName, "ModifiedBy"))
            {
                return IsMatch(colName, "ModifiedOn");
            }
            return true;
        }

        public static bool IsLogicalDeleteColumn(string columnName)
        {
            if (!IsMatch(columnName, "Deleted"))
            {
                return IsMatch(columnName, "IsDeleted");
            }
            return true;
        }

        public static bool IsMappingTable(TableSchema.Table schema, string relatedTableColumn)
        {
            if (((((schema.Columns.Count != 2) || !schema.Columns[0].IsPrimaryKey) || (!schema.Columns[0].IsForeignKey || !schema.Columns[1].IsPrimaryKey)) || (!schema.Columns[1].IsForeignKey || (!IsMatch(schema.Columns[0].ColumnName, relatedTableColumn) && !IsMatch(schema.Columns[1].ColumnName, relatedTableColumn)))) && (((((schema.Columns.Count != 3) || !schema.Columns[0].IsPrimaryKey) || (schema.Columns[0].IsForeignKey || !schema.Columns[1].IsPrimaryKey)) || ((!schema.Columns[1].IsForeignKey || !schema.Columns[2].IsPrimaryKey) || !schema.Columns[2].IsForeignKey)) || (!IsMatch(schema.Columns[1].ColumnName, relatedTableColumn) && !IsMatch(schema.Columns[2].ColumnName, relatedTableColumn))))
            {
                return false;
            }
            return true;
        }

        public static bool IsMatch(string stringA, string stringB)
        {
            return string.Equals(stringA, stringB, StringComparison.InvariantCultureIgnoreCase);
        }

        public static bool IsMatch(string stringA, string stringB, bool trimStrings)
        {
            if (trimStrings)
            {
                return string.Equals(stringA.Trim(), stringB.Trim(), StringComparison.InvariantCultureIgnoreCase);
            }
            return string.Equals(stringA, stringB, StringComparison.InvariantCultureIgnoreCase);
        }

        public static bool IsNullableDbType(DbType dbType)
        {
            switch (dbType)
            {
                case DbType.AnsiStringFixedLength:
                case DbType.StringFixedLength:
                case DbType.String:
                case DbType.AnsiString:
                case DbType.Binary:
                case DbType.Object:
                    return false;
            }
            return true;
        }

        public static bool IsNumeric(TableSchema.TableColumn column)
        {
            switch (column.DataType)
            {
                case DbType.Currency:
                case DbType.Decimal:
                case DbType.Double:
                case DbType.Int16:
                case DbType.Int32:
                case DbType.Int64:
                case DbType.Single:
                    return true;
            }
            return false;
        }

        public static bool IsParsable(DbType dbType)
        {
            switch (dbType)
            {
                case DbType.AnsiStringFixedLength:
                case DbType.StringFixedLength:
                case DbType.Object:
                case DbType.String:
                case DbType.AnsiString:
                case DbType.Binary:
                case DbType.Guid:
                    return false;
            }
            return true;
        }

        public static bool IsRegexMatch(string inputString, string matchPattern)
        {
            return Regex.IsMatch(inputString, matchPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
        }

        public static bool IsSql2000(DataProvider provider)
        {
            return (provider.DatabaseVersion.IndexOf("2000 - 8.") > -1);
        }

        public static bool IsSql2005(DataProvider provider)
        {
            return (provider.DatabaseVersion.IndexOf("2005 - 9.") > -1);
        }

        public static bool IsString(TableSchema.TableColumn column)
        {
            bool flag = false;
            DbType dataType = column.DataType;
            if (((dataType != DbType.String) && (dataType != DbType.AnsiString)) && ((dataType != DbType.AnsiStringFixedLength) && (dataType != DbType.StringFixedLength)))
            {
                return flag;
            }
            return true;
        }

        public static bool IsStringNumeric(string str)
        {
            double num;
            return double.TryParse(str, NumberStyles.Float, (IFormatProvider) NumberFormatInfo.CurrentInfo, out num);
        }

        public static bool IsWritableColumn(TableSchema.TableColumn col)
        {
            return (((!IsMatch(col.ColumnName, "CreatedBy") && !IsMatch(col.ColumnName, "CreatedOn")) && ((!col.IsReadOnly && !col.IsPrimaryKey) && !col.AutoIncrement)) || col.IsForeignKey);
        }

        public static string KeyWordCheck(string word, string table, DataProvider provider)
        {
            string appendWith = "X";
            if (!string.IsNullOrEmpty(provider.AppendWith))
            {
                appendWith = provider.AppendWith;
            }
            return KeyWordCheck(word, table, appendWith);
        }

        public static string KeyWordCheck(string word, string table, string appendWith)
        {
            string str = word + appendWith;
            if (word == "Schema")
            {
                str = word + appendWith;
            }
            if (word == table)
            {
                return str;
            }
            switch (word.ToLower())
            {
                case "abstract":
                    return str;

                case "as":
                    return str;

                case "base":
                    return str;

                case "bool":
                    return str;

                case "break":
                    return str;

                case "byte":
                    return str;

                case "case":
                    return str;

                case "catch":
                    return str;

                case "char":
                    return str;

                case "checked":
                    return str;

                case "class":
                    return str;

                case "const":
                    return str;

                case "continue":
                    return str;

                case "date":
                    return str;

                case "datetime":
                    return str;

                case "decimal":
                    return str;

                case "default":
                    return str;

                case "delegate":
                    return str;

                case "do":
                    return str;

                case "double":
                    return str;

                case "else":
                    return str;

                case "enum":
                    return str;

                case "event":
                    return str;

                case "explicit":
                    return str;

                case "extern":
                    return str;

                case "false":
                    return str;

                case "finally":
                    return str;

                case "fixed":
                    return str;

                case "float":
                    return str;

                case "for":
                    return str;

                case "foreach":
                    return str;

                case "goto":
                    return str;

                case "if":
                    return str;

                case "implicit":
                    return str;

                case "in":
                    return str;

                case "int":
                    return str;

                case "interface":
                    return str;

                case "internal":
                    return str;

                case "is":
                    return str;

                case "lock":
                    return str;

                case "long":
                    return str;

                case "namespace":
                    return str;

                case "new":
                    return str;

                case "null":
                    return str;

                case "object":
                    return str;

                case "operator":
                    return str;

                case "out":
                    return str;

                case "override":
                    return str;

                case "params":
                    return str;

                case "private":
                    return str;

                case "protected":
                    return str;

                case "public":
                    return str;

                case "readonly":
                    return str;

                case "ref":
                    return str;

                case "return":
                    return str;

                case "sbyte":
                    return str;

                case "sealed":
                    return str;

                case "short":
                    return str;

                case "sizeof":
                    return str;

                case "stackalloc":
                    return str;

                case "static":
                    return str;

                case "string":
                    return str;

                case "struct":
                    return str;

                case "switch":
                    return str;

                case "this":
                    return str;

                case "throw":
                    return str;

                case "true":
                    return str;

                case "try":
                    return str;

                case "typeof":
                    return str;

                case "uint":
                    return str;

                case "ulong":
                    return str;

                case "unchecked":
                    return str;

                case "unsafe":
                    return str;

                case "ushort":
                    return str;

                case "using":
                    return str;

                case "virtual":
                    return str;

                case "volatile":
                    return str;

                case "void":
                    return str;

                case "while":
                    return str;

                case "get":
                    return str;

                case "partial":
                    return str;

                case "set":
                    return str;

                case "value":
                    return str;

                case "where":
                    return str;

                case "yield":
                    return str;

                case "alias":
                    return str;

                case "addHandler":
                    return str;

                case "ansi":
                    return str;

                case "assembly":
                    return str;

                case "auto":
                    return str;

                case "binary":
                    return str;

                case "byref":
                    return str;

                case "byval":
                    return str;

                case "custom":
                    return str;

                case "directcast":
                    return str;

                case "each":
                    return str;

                case "elseif":
                    return str;

                case "end":
                    return str;

                case "error":
                    return str;

                case "friend":
                    return str;

                case "global":
                    return str;

                case "handles":
                    return str;

                case "implements":
                    return str;

                case "lib":
                    return str;

                case "loop":
                    return str;

                case "me":
                    return str;

                case "module":
                    return str;

                case "mustinherit":
                    return str;

                case "mustoverride":
                    return str;

                case "mybase":
                    return str;

                case "myclass":
                    return str;

                case "narrowing":
                    return str;

                case "next":
                    return str;

                case "nothing":
                    return str;

                case "notinheritable":
                    return str;

                case "notoverridable":
                    return str;

                case "of":
                    return str;

                case "off":
                    return str;

                case "on":
                    return str;

                case "option":
                    return str;

                case "optional":
                    return str;

                case "overloads":
                    return str;

                case "overridable":
                    return str;

                case "overrides":
                    return str;

                case "paramarray":
                    return str;

                case "preserve":
                    return str;

                case "property":
                    return str;

                case "raiseevent":
                    return str;

                case "resume":
                    return str;

                case "shadows":
                    return str;

                case "shared":
                    return str;

                case "step":
                    return str;

                case "structure":
                    return str;

                case "text":
                    return str;

                case "then":
                    return str;

                case "to":
                    return str;

                case "trycast":
                    return str;

                case "unicode":
                    return str;

                case "until":
                    return str;

                case "when":
                    return str;

                case "widening":
                    return str;

                case "withevents":
                    return str;

                case "writeonly":
                    return str;

                case "compare":
                    return str;

                case "isfalse":
                    return str;

                case "istrue":
                    return str;

                case "mid":
                    return str;

                case "strict":
                    return str;

                case "schema":
                    return str;
            }
            return word;
        }

        public static string KeyWordVBCheck(string word, string table, DataProvider provider)
        {
            return KeyWordCheck(word, table, provider);
        }

        public static void LoadDropDown(DropDownList ddl, IDataReader rdr, bool closeReader)
        {
            ddl.Items.Clear();
            while (rdr.Read())
            {
                string text = rdr[1].ToString();
                string str2 = rdr[0].ToString();
                ddl.Items.Add(new ListItem(text, str2));
            }
            if (closeReader)
            {
                rdr.Close();
            }
        }

        public static void LoadDropDown(DropDownList ddl, ICollection collection, string textField, string valueField, string initialSelection)
        {
            ddl.DataSource = collection;
            ddl.DataTextField = textField;
            ddl.DataValueField = valueField;
            ddl.DataBind();
            ddl.SelectedValue = initialSelection;
        }

        public static void LoadListItems(ListItemCollection list, DataTable tblBind, DataTable tblVals, string textField, string valField)
        {
            for (int i = 0; i < tblBind.Rows.Count; i++)
            {
                ListItem item = new ListItem(tblBind.Rows[i][textField].ToString(), tblBind.Rows[i][valField].ToString());
                for (int j = 0; j < tblVals.Rows.Count; j++)
                {
                    DataRow row = tblVals.Rows[j];
                    if (IsMatch(row[valField].ToString(), item.Value))
                    {
                        item.Selected = true;
                    }
                }
                list.Add(item);
            }
        }

        public static void LoadListItems(ListItemCollection list, IDataReader rdr, string textField, string valField, string selectedValue, bool closeReader)
        {
            list.Clear();
            while (rdr.Read())
            {
                string text = rdr[textField].ToString();
                string str2 = rdr[valField].ToString();
                ListItem item = new ListItem(text, str2);
                if (!string.IsNullOrEmpty(selectedValue) && IsMatch(selectedValue, str2))
                {
                    item.Selected = true;
                }
                list.Add(item);
            }
            if (closeReader)
            {
                rdr.Close();
            }
        }

        public static string MakeFunction(string functionName, string columnName, DataProvider provider)
        {
            return (functionName + "(" + provider.DelimitDbName(columnName) + ")");
        }

        public static string MakeFunction(string functionName, string columnName, bool isDistinct, DataProvider provider)
        {
            if (isDistinct)
            {
                return (functionName + "(DISTINCT " + provider.DelimitDbName(columnName) + ")");
            }
            return MakeFunction(functionName, columnName, provider);
        }

        public static string MakeParameterAssignment(string columnName, string parameterName, DataProvider provider)
        {
            return (provider.DelimitDbName(columnName) + " = " + PrefixParameter(parameterName, provider));
        }

        public static string ParseCamelToProper(string sIn)
        {
            if (Validation.IsUpperCase(sIn))
            {
                return sIn;
            }
            char[] chArray = sIn.ToCharArray();
            StringBuilder builder = new StringBuilder();
            int num = 0;
            if (sIn.Contains("ID"))
            {
                builder.Append(chArray[0]);
                builder.Append(sIn.Substring(1, sIn.Length - 1));
            }
            else
            {
                foreach (char ch in chArray)
                {
                    if (num == 0)
                    {
                        builder.Append(" ");
                        builder.Append(ch.ToString().ToUpper());
                    }
                    else if (char.IsUpper(ch))
                    {
                        builder.Append(" ");
                        builder.Append(ch);
                    }
                    else
                    {
                        builder.Append(ch);
                    }
                    num++;
                }
            }
            return builder.ToString().Trim();
        }

        public static string PluralToSingular(string sIn)
        {
            return Inflector.MakeSingular(sIn);
        }

        public static string PrefixParameter(string parameter, DataProvider provider)
        {
            string parameterPrefix = provider.GetParameterPrefix();
            if (!parameter.StartsWith(parameterPrefix))
            {
                parameter = parameterPrefix + parameter;
            }
            return parameter;
        }

        public static string QualifyColumnName(string tableName, string columnName, DataProvider provider)
        {
            string str = provider.DelimitDbName(tableName);
            if (!string.IsNullOrEmpty(str))
            {
                return (str + "." + provider.DelimitDbName(columnName));
            }
            return provider.DelimitDbName(columnName);
        }

        public static string QualifyTableName(string schemaName, string tableName, DataProvider provider)
        {
            return (provider.DelimitDbName(schemaName) + "." + provider.DelimitDbName(tableName));
        }

        private static int RandomInt(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

        private static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < size; i++)
            {
                char ch = Convert.ToChar(Convert.ToInt32((double) ((26.0 * random.NextDouble()) + 65.0)));
                builder.Append(ch);
            }
            if (lowerCase)
            {
                return builder.ToString().ToLower();
            }
            return builder.ToString();
        }

        public static string RegexTransform(string inputText, DataProvider provider)
        {
            if (provider.UseRegexReplace)
            {
                Regex regex;
                if (!string.IsNullOrEmpty(provider.RegexMatchExpression))
                {
                    if (!provider.RegexIgnoreCase)
                    {
                        regex = new Regex(provider.RegexMatchExpression);
                    }
                    else
                    {
                        regex = new Regex(provider.RegexMatchExpression, RegexOptions.IgnoreCase);
                    }
                    inputText = regex.Replace(inputText, provider.RegexReplaceExpression);
                }
                if (!string.IsNullOrEmpty(provider.RegexDictionaryReplace) && !string.IsNullOrEmpty(inputText))
                {
                    foreach (string str2 in Regex.Split(Regex.Replace(provider.RegexDictionaryReplace, "[\r\n\t]", string.Empty), ";"))
                    {
                        string[] strArray2 = Regex.Split(str2, ",");
                        if (strArray2.Length == 2)
                        {
                            if (!provider.RegexIgnoreCase)
                            {
                                regex = new Regex(strArray2[0]);
                            }
                            else
                            {
                                regex = new Regex(strArray2[0], RegexOptions.IgnoreCase);
                            }
                            inputText = regex.Replace(inputText, strArray2[1]);
                        }
                    }
                }
            }
            return inputText;
        }

        public static string Replace(string word, string find, string replaceWith, bool removeUnderscores)
        {
            string[] strArray = Split(find);
            string str = word;
            foreach (string str2 in strArray)
            {
                if (str2.Length > 0)
                {
                    str = str.Replace(str2, replaceWith);
                }
            }
            if (removeUnderscores)
            {
                return str.Replace(" ", "").Replace("_", "").Trim();
            }
            return str.Replace(" ", "").Trim();
        }

        public static void SetListSelection(ListItemCollection lc, string Selection)
        {
            for (int i = 0; i < lc.Count; i++)
            {
                if (lc[i].Value == Selection)
                {
                    lc[i].Selected = true;
                    return;
                }
            }
        }

        public static string ShortenText(object sIn, int length)
        {
            string str = sIn.ToString();
            if (str.Length > length)
            {
                str = str.Substring(0, length) + " ...";
            }
            return str;
        }

        public static string SingularToPlural(string sIn)
        {
            return Inflector.MakePlural(sIn);
        }

        public static string[] Split(string list)
        {
            try
            {
                return list.Split(new string[] { ", ", "," }, StringSplitOptions.RemoveEmptyEntries);
            }
            catch
            {
                return new string[] { string.Empty };
            }
        }

        public static bool StartsWith(string word, string list)
        {
            if (string.IsNullOrEmpty(list))
            {
                return true;
            }
            foreach (string str in Split(list))
            {
                if (word.StartsWith(str, StringComparison.CurrentCultureIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }

        public static byte[] StringToByteArray(string str)
        {
            Encoding aSCII = Encoding.ASCII;
            Encoding unicode = Encoding.Unicode;
            byte[] bytes = unicode.GetBytes(str);
            return Encoding.Convert(unicode, aSCII, bytes);
        }

        public static object StringToEnum(Type t, string Value)
        {
            object obj2 = null;
            foreach (FieldInfo info in t.GetFields())
            {
                if (IsMatch(info.Name, Value))
                {
                    obj2 = info.GetValue(null);
                }
            }
            return obj2;
        }

        public static string StripHTML(string htmlString)
        {
            return StripHTML(htmlString, "", true);
        }

        public static string StripHTML(string htmlString, string htmlPlaceHolder)
        {
            return StripHTML(htmlString, htmlPlaceHolder, true);
        }

        public static string StripHTML(string htmlString, string htmlPlaceHolder, bool stripExcessSpaces)
        {
            string pattern = @"<(.|\n)*?>";
            string str2 = Regex.Replace(htmlString, pattern, htmlPlaceHolder).Replace("&nbsp;", "").Replace("&amp;", "&");
            if (!stripExcessSpaces)
            {
                return str2;
            }
            char[] separator = new char[] { ' ' };
            string[] strArray = str2.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder builder = new StringBuilder();
            foreach (string str3 in strArray)
            {
                builder.Append(str3);
                builder.Append(" ");
            }
            return builder.ToString().Trim();
        }

        public static string StripNonAlphaNumeric(string sIn)
        {
            StringBuilder builder = new StringBuilder(sIn);
            char newChar = " ".ToCharArray()[0];
            string str = ".'?\\/><$!@%^*&+,;:\"{}[]|-#";
            for (int i = 0; i < str.Length; i++)
            {
                builder.Replace(str[i], newChar);
            }
            builder.Replace(" ", string.Empty);
            return builder.ToString();
        }

        public static string StripText(string inputString, string stripString)
        {
            if (!string.IsNullOrEmpty(stripString))
            {
                string[] strArray = stripString.Split(new char[] { ',' });
                for (int i = 0; i < strArray.Length; i++)
                {
                    if (!string.IsNullOrEmpty(inputString))
                    {
                        inputString = Regex.Replace(inputString, strArray[i], string.Empty);
                    }
                }
            }
            return inputString;
        }

        public static string StripWhitespace(string inputString)
        {
            if (!string.IsNullOrEmpty(inputString))
            {
                return Regex.Replace(inputString, @"\s", string.Empty);
            }
            return inputString;
        }

        public static string ToggleHtmlBR(string text, bool isOn)
        {
            if (isOn)
            {
                return text.Replace(Environment.NewLine, "<br />");
            }
            return text.Replace("<br />", Environment.NewLine).Replace("<br>", Environment.NewLine).Replace("<br >", Environment.NewLine);
        }

        public static bool UserIsAuthenticated()
        {
            HttpContext current = HttpContext.Current;
            return (((current.User != null) && (current.User.Identity != null)) && !string.IsNullOrEmpty(current.User.Identity.Name));
        }

        public static void WriteTrace(string message)
        {
            if (DataService.EnableTrace)
            {
                if ((HttpContext.Current != null) && HttpContext.Current.Trace.IsEnabled)
                {
                    message = DateTime.Now.ToString("H:mm:ss:fff") + " > " + message;
                    HttpContext.Current.Trace.Write("SubSonic", message);
                }
                else if (Debug.Listeners.Count > 0)
                {
                    message = DateTime.Now.ToString("H:mm:ss:fff") + " > " + message;
                    Console.WriteLine(message);
                }
            }
        }
    }
}

